﻿using System;
using System.Collections;
using System.Collections.Generic;
using BehaviorDesigner.Runtime.Tasks.Basic.UnityDebug;
using UnityEngine;


public class Projectile : MonoBehaviour
{
    public bool isHit;
    public bool isSetTarget;
    public float _moveSpeed;
    public GameObject hitAnimationPrefab;
    
    public Vector3 targetPoint;

    public void SetTargetPoint(Vector3 targetPoint)
    {
        Debug.Log("Set Position");
        this.targetPoint = targetPoint;
        this.targetPoint.z = -1;
        
        this.isSetTarget = true;
    }

    private void Update()
    {
        if (!isSetTarget) return;
        
        Move();
        if(CheckIsReachTarget())
        {
            isSetTarget = false;
            PlayHitEffect();
            Destroy(gameObject, .5f);
        }
    }

    private void Move()
    {
        var position = transform.position;
        float newDir = -Vector2.SignedAngle(targetPoint - position, Vector2.up);

        transform.eulerAngles = new Vector3(0, 0, newDir);
        
        position = Vector2.MoveTowards(position, targetPoint, _moveSpeed * Time.deltaTime);
        position.z = -1;
        transform.position = position;
    }
    
    private bool CheckIsReachTarget()
    {
        Vector2 diff = transform.position - targetPoint;
        return (Mathf.RoundToInt(diff.x) == 0 && Mathf.RoundToInt(diff.y) == 0);
    }

    private void PlayHitEffect()
    {
        if (hitAnimationPrefab)
        {
            GetComponent<SpriteRenderer>().enabled = false;
            GameObject.Instantiate(hitAnimationPrefab, transform.position, Quaternion.identity);
            isHit = true;
        }
    }
    
}
